<?php


namespace app\mingteng\controller;
use think\AjaxPage;
use think\Db;

class Rechargeable extends Base
{

    public $listRows = 20;

    /**
     *虚拟卡页面
     * @return mixed
     */
    public function index(){
        return $this->fetch();
    }

    /**
     * 实体卡页面
     * @return mixed
     */
    public function entity_index(){
        return $this->fetch();
    }

    public function password_view(){

        $admin_id = session('admin_id');

        return $admin_id;
    }

    /**
     * 虚拟卡列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ajax_index(){
        $params = input('post.');
        $page = input('page', '1');

        $where = array();
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $where['card_number'] = array('=', $params['keywords']);
        }
        if (isset($params['states']) && !empty($params['states'])) {
            $where['states'] = array('=', $params['states']);
        }
        if (isset($params['useTo']) && !empty($params['useTo'])) {
            $where['useTo'] = array('=', $params['useTo']);
        }
        if (isset($params['activation_type']) && !empty($params['activation_type'])) {
            $where['activation_type'] = array('=', $params['activation_type']);
        }
        if(isset($params['time_frame']) && !empty($params['time_frame'])){
            $start_time = substr($params['time_frame'],0,19);
            $end_time = substr($params['time_frame'],-19);
            $where['createtime'] = ['between time',[$start_time,$end_time]];
        }

        $where['rechargeableIsDel'] = 0;
        $where['types'] = 1;
        $count = Db::name('rechargeable')->where($where)->count();
        $list = Db::name('rechargeable')->where($where)->order('id','desc')->page($page, $this->listRows)->select();
        foreach($list as $k=>$v){
            if($v['states'] == 2){
                $list[$k]['states'] = '已使用';
            }else{
                $list[$k]['states'] = '正常';
            }
            $list[$k]['createtime'] = date('Y-m-d H:i',$v['createtime']);
            $list[$k]['usagetime'] = $v['usagetime']?date('Y-m-d H:i',$v['usagetime']):'--';
        }
        $this->assign('list', $list);

        $ajaxPage = new AjaxPage($count, $this->listRows);
        $show = $ajaxPage->show();
        $this->assign('page', $show);

        $admin_id = $this->password_view();
        $role_id = Db::name('admin')->where('admin_id',$admin_id)->value('role_id');
        $role = Db::name('admin_role')->where('role_id',$role_id)->value('act_list');
        if($role == 'all'){
            $viewType = 1;
        }else{
            if(in_array(19,explode(',',$role))){
                $viewType = 1;
            }else{
                $viewType = 2;
            }
        }
        $this->assign('viewType', $viewType);

        return $this->fetch();
    }

    /**
     * 实体卡列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ajax_entity_index(){
        $params = input('post.');
        $page = input('page', '1');

        $where = array();
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $where['card_number'] = array('=', $params['keywords']);
        }
        if (isset($params['states']) && !empty($params['states'])) {
            $where['states'] = array('=', $params['states']);
        }
        if (isset($params['activation_type']) && !empty($params['activation_type'])) {
            $where['activation_type'] = array('=', $params['activation_type']);
        }
        if(isset($params['time_frame']) && !empty($params['time_frame'])){
            $start_time = substr($params['time_frame'],0,19);
            $end_time = substr($params['time_frame'],-19);
            $where['createtime'] = ['between time',[$start_time,$end_time]];
        }

        $where['rechargeableIsDel'] = 0;
        $where['types'] = 2;
        $count = Db::name('rechargeable')->where($where)->count();
        $list = Db::name('rechargeable')->where($where)->order('id','desc')->page($page, $this->listRows)->select();
        foreach($list as $k=>$v){
            if($v['states'] == 2){
                $list[$k]['states'] = '已使用';
            }else{
                $list[$k]['states'] = '正常';
            }
            $list[$k]['createtime'] = date('Y-m-d H:i',$v['createtime']);
            $list[$k]['usagetime'] = $v['usagetime']?date('Y-m-d H:i',$v['usagetime']):'--';
            $list[$k]['userMobile'] = Db::name('user')->where('userId',$v['use_user'])->value('userMobile');
        }
        $this->assign('list', $list);

        $ajaxPage = new AjaxPage($count, $this->listRows);
        $show = $ajaxPage->show();
        $this->assign('page', $show);

        $admin_id = $this->password_view();
        $role_id = Db::name('admin')->where('admin_id',$admin_id)->value('role_id');
        $role = Db::name('admin_role')->where('role_id',$role_id)->value('act_list');
        if($role == 'all'){
            $viewType = 1;
        }else{
            if(in_array(19,explode(',',$role))){
                $viewType = 1;
            }else{
                $viewType = 2;
            }
        }
        $this->assign('viewType', $viewType);

        return $this->fetch();
    }

    public function add(){

        return $this->fetch();
    }


    public function doAdd(){
        $params = input('post.');

        if ($params['types'] <= 0) {
            return json(array('code' => 500, 'msg' => '请选择充值卡类型'));
        }

        if (empty($params['denomination'])) {
            return json(array('code' => 500, 'msg' => '请选择面额'));
        }

        $model = new \app\mingteng\model\Rechargeable();
        if($params['types'] == 1){
            //虚拟卡
//            if (empty($params['userMobile'])) {
//                return json(array('code' => 500, 'msg' => '请输入给予用户电话'));
//            }
//            if (empty($params['useTo'])) {
//                return json(array('code' => 500, 'msg' => '请选择用途'));
//            }
            $user = Db::name('user')->where('userMobile',$params['userMobile'])->field('userId,nickName')->find();
//            if(empty($user)){
//                return json(array('code' => 500, 'msg' => '没有找到该用户'));
//            }

            $card_set = Db::name('card_set')->where('amount',$params['denomination'])->find();
            if($card_set){
                $params['substantialCharge'] = $card_set['reality_amount'];
            }
            $data = $model->virtually($params,$user);

        }else{
            //实体卡
            if ($params['number'] <= 0){
                return json(array('code' => 500, 'msg' => '请输入正确的数量'));
            }

            $data = $model->entity($params);
        }
        if($data){
            return json(array('code' => 200, 'msg' => '添加成功'));
        }else{
            return json(array('code' => 500, 'msg' => '添加失败'));
        }

    }


    public function edit(){
        $id = input('id');

        $rechargeable = Db::name('rechargeable')->where('id', '=', $id)->find();
        $this->assign('rechargeable', $rechargeable);

        return $this->fetch();
    }

    public function doEdit(){
        $params = input('post.');
        $user = Db::name('user')->where('userMobile',$params['userMobile'])->field('userId,nickName')->find();
//        if(empty($user)){
//            return json(array('code' => 500, 'msg' => '没有找到该用户'));
//        }
        $states = Db::name('rechargeable')->where('id', '=', $params['id'])->value('states');
        if($states == 1){
            return json(array('code' => 500, 'msg' => '该充值卡已使用，不能修改'));
        }
//        if (empty($params['userMobile'])) {
//            return json(array('code' => 500, 'msg' => '请输入给予用户电话'));
//        }
        if ($params['types'] <= 0) {
            return json(array('code' => 500, 'msg' => '请输入充值卡类型'));
        }
        if (empty($params['denomination'])) {
            return json(array('code' => 500, 'msg' => '请输入面额'));
        }

        $catch = array(
            'userMobile' => $params['userMobile'],
            'types' => $params['types'],
            'denomination' => $params['denomination'],
            'substantialCharge' => $params['substantialCharge'],
            'useTo' => $params['useTo'],
        );
        Db::name('rechargeable')->where('id', '=', $params['id'])->update($catch);
        return json(array('code' => 200, 'msg' => '编辑成功'));
    }

    public function del(){
        $del_id = input('del_id');

        Db::name('rechargeable')->where('id', '=', $del_id)->save(array(
            'rechargeableIsDel' => '1',
        ));
        return json(array('code' => 200, 'msg' => '操作成功'));
    }

    /**
     * 充值卡设置页面
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function card_set_index(){

        return $this->fetch();
    }

    public function ajax_card_set_index(){

        $count = Db::name('card_set')->count();
        $data = Db::name('card_set')->select();
        foreach($data as $k=>$v){

            $data[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
        }

        $ajaxPage = new AjaxPage($count, $this->listRows);
        $show = $ajaxPage->show();

        $this->assign('page', $show);
        $this->assign('data', $data);

        return $this->fetch();
    }

    public function card_set_del(){

        $del_id = input('del_id');

        Db::name('card_set')->where('id', '=', $del_id)->delete();
        return json(array('code' => 200, 'msg' => '操作成功'));
    }

    public function add_card_set(){

        return $this->fetch();
    }

    public function do_add_card_set(){

        $params = input('post.');

        if ($params['amount'] < 0 || $params['reality_amount'] < 0){
            return json(array('code' => 500, 'msg' => '请输入正确的金额'));
        }

        $params['createtime'] = time();
        $data = Db::name('card_set')->insert($params);

        if($data){
            return json(array('code' => 200, 'msg' => '添加成功'));
        }else{
            return json(array('code' => 500, 'msg' => '添加失败'));
        }
    }

    public function edit_card_set(){

        $id = input('id');

        $data = Db::name('card_set')->where('id', '=', $id)->find();
        $this->assign('data', $data);

        return $this->fetch();
    }

    public function do_edit_card_set(){

        $params = input();

        if(empty($params['id'])){
            return json(array('code' => 500, 'msg' => '参数错误'));
        }
        if ($params['amount'] < 0 || $params['reality_amount'] < 0){
            return json(array('code' => 500, 'msg' => '请输入正确的金额'));
        }

        $id = $params['id'];
        unset($params['id']);
        $data = Db::name('card_set')->where('id',$id)->update($params);

        if($data){
            return json(array('code' => 200, 'msg' => '成功'));
        }else{
            return json(array('code' => 500, 'msg' => '失败'));
        }

    }

    /**
     * 激活充值卡
     * @return \think\response\Json
     */
    public function activation(){

        $id = input('id');
       if(empty($id)){
           return json(array('code' => 500, 'msg' => 'id不能为空'));
       }

        Db::name('rechargeable')->where('id', '=', $id)->save(array(
            'activation_type' => '2',
        ));
        return json(array('code' => 200, 'msg' => '操作成功'));
    }

    /**
     * 批量激活充值卡
     * @return \think\response\Json
     */
    public function activationAll(){
        $ids = input('ids/a');
        if(empty($ids)){
            return json(array('code' => 500, 'msg' => '请选择需要激活的充值卡'));
        }

        Db::name('rechargeable')->where('id', 'in', $ids)->save(array(
            'activation_type' => '2',
        ));
        return json(array('code' => 200, 'msg' => '操作成功'));
    }

    /**
     * 导出
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function export(){

        $ids = input('ids');
        if(empty($ids)){
            return json(array('code' => 500, 'msg' => 'id不能为空'));
        }
        $ids =explode(',',$ids);
        $list = Db::name('rechargeable')->where('id','in',$ids)->field('card_number,card_password,denomination')->select();

        //导出
        $expTitle = '充值卡导出';

        $expCellName = array(
            array('card_number','卡号'),
            array('card_password','卡密'),
            array('denomination','面额'),
        );

        $this->expExcel($expTitle,$expCellName,$list);
    }

    /**
     * eccel导出
     * @param string $expTitle 文件名称
     * @param array $expCellName 表头标题
     * @param array $expTableData 数据
     * @return void
     */
    public static function expExcel($expTitle,$expCellName,$expTableData){

        $cellNum = count($expCellName);
        $dataNum = $expTableData?count($expTableData):0;

        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M',
            'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
            'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM',
            'AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

        $objPHPExcel = new \PHPExcel();
        //激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);

        //设置表格头（即excel表格的第一行）
        foreach ($expCellName as $a=>$b) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$a] . '1', $b[1]);
        }

        foreach ($cellName as $v){
            $objPHPExcel->getActiveSheet()->getStyle($v.'1')->getFont()->setBold(true);   // 设置头部字体加粗
            $objPHPExcel->setActiveSheetIndex(0)->getStyle($v.'1')->getAlignment()        // 设置表格头水平居中
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle($v)->getAlignment()            //设置列水平居中
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension($v)->setWidth(30);  //设置单元格宽度
        }

        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+2), $expTableData[$i][$expCellName[$j][0]]);
            }

        }
        //7.设置保存的Excel表格名称
        $filename = $expTitle . date('ymd', time()) . '.xls';
        //8.设置当前激活的sheet表格名称
        $objPHPExcel->getActiveSheet()->setTitle($expTitle);
        //9.设置浏览器窗口下载表格
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $filename . '"');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        exit;
    }

}